package cn.gok.thread;

import java.util.Random;

//消费者线程
public class ConsumeThread extends Thread{
    private WareHouse house;//共享数据

    public ConsumeThread(WareHouse house) {
        this.house = house;
    }
    private Random rd = new Random();
    @Override   //线程方法，不断的消费商品
    public void run() {
        while(true){
            synchronized (house) {
                String product = house.consume();
                if (product != null) {
                    System.out.println("从仓库消费：" + product);
                    continue;
                }
                //以下代码为商品为null的情况，需要进入等待状态！！！
                System.out.println("仓库为空，无法消费商品！进入等待...");
                try {
                    house.wait(); //本线程进入等待状态，释放同步锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (String.class) {
                    product = house.consume();
                    if(product!=null)
                        System.out.println("结束等待，从仓库消费：" + product);
                    else
                        continue;
                }
            }
            try {
                Thread.sleep(rd.nextInt(1500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
